#include "println.h" 

//Global variables ----------
unsigned char *videomem = (unsigned char *)0xB8000; /*adress of video memory*/
textBuffer_t textBuffer;

//textBuffer_t functions ----------

void clearBuffer(){
	int i;

	for(i=0;i<(_NL*_NC*2);i+=2){
		textBuffer.text[i] = ' ';
		textBuffer.text[i+1] = 0x00;	
	}

	textBuffer.currentLine=0;
}

void initBuffer(){
	clearBuffer();
}

void printBuffer(){
	int i;

	for(i=0;i<(_NL*_NC*2);i+=2){
		videomem[i] = textBuffer.text[i];
		videomem[i+1] = textBuffer.text[i+1];	
	}
}

void bufferPrint(char *string){
	int i,h;

	//roll text
	if(textBuffer.currentLine==_NL){
		for(i=0;i<_NL-1;i++)
			for(h=0;h<_NC*2;h++)			
				textBuffer.text[i*_NC*2+h] = textBuffer.text[(i+1)*_NC*2+h];
		for(i=0;i<_NC*2;i+=2){ //Erase last line
			textBuffer.text[(_NL-1)*_NC*2+i] = ' ';
			textBuffer.text[(_NL-1)*_NC*2+i+1] = 0x00;
		}
		textBuffer.currentLine = _NL-1;
	}

	//print in buffer
	for(i=0;string[i]!=0 && i<_NC;i++){
		textBuffer.text[textBuffer.currentLine*_NC*2+i*2] = (unsigned char)string[i];
		textBuffer.text[textBuffer.currentLine*_NC*2+i*2+1] = 0x0F;
	}	
	if(i==_NC){
		textBuffer.currentLine++;
		bufferPrint(&(string[i]));
	}
}

void bufferPrintLine(char *string){
	int i,h;

	//roll text
	if(textBuffer.currentLine==_NL){
		for(i=0;i<_NL-1;i++)
			for(h=0;h<_NC*2;h++)			
				textBuffer.text[i*_NC*2+h] = textBuffer.text[(i+1)*_NC*2+h];
		for(i=0;i<_NC*2;i+=2){ //Erase last line
			textBuffer.text[(_NL-1)*_NC*2+i] = ' ';
			textBuffer.text[(_NL-1)*_NC*2+i+1] = 0x00;
		}
		textBuffer.currentLine = _NL-1;
	}

	//print in buffer
	for(i=0;string[i]!=0 && i<_NC;i++){
		textBuffer.text[textBuffer.currentLine*_NC*2+i*2] = (unsigned char)string[i];
		textBuffer.text[textBuffer.currentLine*_NC*2+i*2+1] = 0x0F;
	}	
	textBuffer.currentLine++;
	if(i==_NC)
		bufferPrintLine(&(string[i]));
}

void print(char *string){
	bufferPrint(string);
	printBuffer();
}

void printLine(char *string){
	bufferPrintLine(string);
	printBuffer();
}

void itoa(unsigned long n,char *c){
	unsigned long comp, teste, pos=0, nn=n;
	for(comp=1000000000;comp>=1;comp/=10){
		teste = nn / comp;	
		nn -= teste*comp;
		if(teste > 0 || pos > 0)
			c[pos++] = teste+48;	
	}
	if(pos == 0){
		c[pos++] = 48;
	}
	c[pos] = 0;
}
